package com.brush.brushcommon.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: MybatisPlusConfig分页配置
 */
@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig {
    //
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setDbType(DbType.MYSQL);//
        paginationInnerInterceptor.setOverflow(true);//解决分页bug
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }

    /**
     * 操作时自动填充createdDate和lastModifiedDate
     *
     * @return
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                Object gmtCreated = getFieldValByName("gmtCreate",metaObject);
                Object gmtModified = getFieldValByName("gmtModified",metaObject);
                if (gmtCreated == null) {
                    setFieldValByName("gmtCreate", LocalDateTime.now(), metaObject);
                }
                if (gmtModified == null) {
                    setFieldValByName("gmtModified", LocalDateTime.now(), metaObject);
                }
            }
            @Override
            public void updateFill(MetaObject metaObject) {
                setFieldValByName("gmtModified", LocalDateTime.now(), metaObject);
            }
        };
    }
}
